package xzit.gcxy.xxhzx.zhh.controller;

import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.DetachedCriteria;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import xzit.gcxy.xxhzx.zhh.client.Client;
import xzit.gcxy.xxhzx.zhh.common.AjaxJson;
import xzit.gcxy.xxhzx.zhh.common.Pagination;
import xzit.gcxy.xxhzx.zhh.common.ResourceUtil;
import xzit.gcxy.xxhzx.zhh.entity.ManagedAccountVO;
import xzit.gcxy.xxhzx.zhh.entity.ScienceWorkDetailVO;
import xzit.gcxy.xxhzx.zhh.entity.ScienceWorkTypeVO;
import xzit.gcxy.xxhzx.zhh.entity.ScienceWorkWeightVO;
import xzit.gcxy.xxhzx.zhh.entity.TeacherInfoVO;
import xzit.gcxy.xxhzx.zhh.entity.TeacherSWTotalVO;
import xzit.gcxy.xxhzx.zhh.service.ScienceWorkService;
import xzit.gcxy.xxhzx.zhh.util.InstituteUtil;

@Controller
@RequestMapping("/scienceWorkController")
public class ScienceWorkController {
	private static final Logger logger = Logger.getLogger(ScienceWorkController.class);
	String[] exceltotalHeader = { "工号", "教师姓名", "教师职务", "总分数" };
	String[] exceldetailHeader = { "工号", "姓名", "科研名称", "科研类型", "科研分值", "权重类型", "权重值", "分值" };
	@Autowired
	private ScienceWorkService scienceWorkService;

	/**
	 * 科研工作量详情页
	 * 
	 * @param error
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "goSWDetail")
	public ModelAndView goSWDetail(HttpServletRequest request) {
		return new ModelAndView("app/swdetail");
	}

	@RequestMapping(params = "goSWTotal")
	public ModelAndView goSWTotal(HttpServletRequest request) {
		return new ModelAndView("app/swtotal");
	}

	@RequestMapping(params = "goSWAdd")
	public ModelAndView goSWAdd(HttpServletRequest request) {
		return new ModelAndView("app/swadd");
	}

	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(@RequestParam Map<String, String> valMap) throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("保存成功！");
		j.setSuccess(true);
		TeacherInfoVO tvo = scienceWorkService.get(TeacherInfoVO.class, Integer.parseInt(valMap.get("teacherid")));
		ScienceWorkTypeVO swtvo = scienceWorkService.get(ScienceWorkTypeVO.class,
				Integer.parseInt(valMap.get("swtypeid")));
		ScienceWorkWeightVO swwvo = scienceWorkService.get(ScienceWorkWeightVO.class,
				Integer.parseInt(valMap.get("swweightid")));
		ScienceWorkDetailVO swvo = new ScienceWorkDetailVO();
		swvo.setSwdate(new Date().getYear() + "");
		swvo.setSwname(valMap.get("swname"));
		swvo.setTeacherInfoVO(tvo);
		swvo.setScienceworktype(swtvo);
		swvo.setScienceworkweight(swwvo);
		swvo.setScore(swtvo.getScore() * swwvo.getWeight());
		swvo.setInstituteid(InstituteUtil.getCurrentInstituteId());
		try {
			this.scienceWorkService.save(swvo);
		} catch (Exception e) {
			j.setMsg("保存失败！");
			j.setSuccess(false);
		}
		return j;

	}

	/*
	 * 删除
	 */
	@RequestMapping(params = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson delete(HttpServletRequest request, HttpServletResponse response, String ids) throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("删除成功！");
		j.setSuccess(true);
		try {
			for (String id : ids.split(",")) {
				ScienceWorkDetailVO scienceWorkDetailVO = scienceWorkService.get(ScienceWorkDetailVO.class,
						Integer.parseInt(id));
				this.scienceWorkService.delete(scienceWorkDetailVO);
			}
		} catch (Exception e) {
			j.setMsg("删除失败！");
			j.setSuccess(false);
		}
		return j;

	}

	@RequestMapping(params = "datagrid")
	@ResponseBody
	public void datagrid(HttpServletRequest request, HttpServletResponse response, ScienceWorkDetailVO ve,
			String gonghao) throws Exception {
		String page = request.getParameter("page");// easyui datagrid 分页 页号
		String rows = request.getParameter("rows");// easyui datagrid 分页 页数
		if (page == null) {
			page = "0";
		}
		if (rows == null) {
			rows = "0";
		}

		Client client = ResourceUtil.getClient();
		ManagedAccountVO user = client.getUser();
		int instituteId = user.getInstitute().getInstituteid();

		DetachedCriteria condition = DetachedCriteria.forClass(ScienceWorkDetailVO.class);
		Pagination<?> pagination = scienceWorkService.findPageData(condition, ve, gonghao, instituteId,
				Integer.parseInt(page), Integer.parseInt(rows));

		JSONObject jobj = new JSONObject();
		jobj.put("total", pagination.getTotalCount());
		jobj.put("rows", pagination.getDatas());

		response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());

	}

	@RequestMapping(params = "totaldatagrid")
	@ResponseBody
	public void totalDatagrid(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String page = request.getParameter("page");// easyui datagrid 分页 页号
		String rows = request.getParameter("rows");// easyui datagrid 分页 页数
		if (page == null) {
			page = "0";
		}
		if (rows == null) {
			rows = "0";
		}

		Client client = ResourceUtil.getClient();
		ManagedAccountVO user = client.getUser();
		int instituteId = user.getInstitute().getInstituteid();

		Pagination<?> pagination = scienceWorkService.findPageData(Integer.parseInt(page), Integer.parseInt(rows));

		JSONObject jobj = new JSONObject();
		jobj.put("total", pagination.getTotalCount());
		jobj.put("rows", pagination.getDatas());

		response.setCharacterEncoding("utf-8");
		response.getWriter().write(jobj.toString());

	}

	/*
	 * 导出所有工作量信息
	 */
	@RequestMapping(params = "exporttotalExcel")
	public void exportTotalExcel(HttpServletRequest request, HttpServletResponse response, String teachername,
			String coursename, String term, String name) throws Exception {
		List<TeacherSWTotalVO> tswList = scienceWorkService.queryTeacherSWTotal();

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("sheet1");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		for (int i = 0; i < exceltotalHeader.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(exceltotalHeader[i]);
			cell.setCellStyle(style);
			sheet.autoSizeColumn(i);
		}

		for (int i = 0; i < tswList.size(); i++) {
			row = sheet.createRow(i + 1);
			TeacherSWTotalVO tswVO = tswList.get(i);
			row.createCell(0).setCellValue(tswVO.getGonghao());
			row.createCell(1).setCellValue(tswVO.getRealname());
			row.createCell(2).setCellValue(tswVO.getBusiness());
			row.createCell(3).setCellValue(tswVO.getTotal());
		}

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=Total-score-statistics-of-scientific-research-work.xls");
		OutputStream ouputStream = response.getOutputStream();
		try {
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ouputStream.flush();
			ouputStream.close();
		}

	}

	/*
	 * 导出所有工作量信息
	 */
	@RequestMapping(params = "expordetaillExcel")
	public void exportDetailExcel(HttpServletRequest request, HttpServletResponse response, String teachername,
			String coursename, String term, String name) throws Exception {
		List<ScienceWorkDetailVO> swdList = scienceWorkService.queryScienceWorkDetailVOs();

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("sheet1");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		for (int i = 0; i < exceldetailHeader.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(exceldetailHeader[i]);
			cell.setCellStyle(style);
			sheet.autoSizeColumn(i);
		}

		for (int i = 0; i < swdList.size(); i++) {
			row = sheet.createRow(i + 1);
			ScienceWorkDetailVO swdVO = swdList.get(i);
			row.createCell(0).setCellValue(swdVO.getTeacherInfoVO().getGonghao());
			row.createCell(1).setCellValue(swdVO.getTeacherInfoVO().getRealname());
			row.createCell(2).setCellValue(swdVO.getSwname());
			row.createCell(3).setCellValue(swdVO.getScienceworktype().getSwtype());
			row.createCell(4).setCellValue(swdVO.getScienceworktype().getScore());
			row.createCell(5).setCellValue(swdVO.getScienceworkweight().getSwweight());
			row.createCell(6).setCellValue(swdVO.getScienceworkweight().getWeight());
			row.createCell(7).setCellValue(swdVO.getScore());
		}

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=Detail-score-statistics-of-scientific-research-work.xls");
		OutputStream ouputStream = response.getOutputStream();
		try {
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ouputStream.flush();
			ouputStream.close();
		}

	}

}
